//
//  TakeDrugsViewController.m
//  安好
//
//  Created by lianchuang on 14-11-12.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "TakeDrugsViewController.h"
#import "UserModel.h"
#import "AddFamilyViewController.h"
#import "TakeDrugReminderViewController.h"
#import "AllFamilyModal.h"
#define CellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1]
#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface TakeDrugsViewController ()<UITableViewDataSource,UITableViewDelegate>

/**
 *  保存我自己的用药提醒
 */
@property(nonatomic,strong)NSArray * myDrugReminderDataArray;
/**
 *  网络菊花转圈的标志，这个页面有2个请求，当两个都结束的时候才能去掉菊花转
 */
@property(nonatomic,assign)NSInteger AFNetFlag;

@end



@implementation TakeDrugsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self makeNavBarView];
    [self loadData];
    [self makeTableView];
    
}
//每次返回来的时候都刷新数据
-(void)viewWillAppear:(BOOL)animated
{
     [self AFNetRequestWithAllFamilyName];
     [self AFNetRequestForMyDrugReminderCount];
}

#pragma mark - 设置导航条
-(void)makeNavBarView
{
    self.navigationItem.title = @"用药提醒";
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    UIButton * addFamilyBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [addFamilyBtn setTitle:@"添加家人" forState:UIControlStateNormal];
    [addFamilyBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    addFamilyBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [addFamilyBtn addTarget:self action:@selector(addBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addFamilyBtn];
    
}
//“返回”
-(void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  navBar右按钮--》添加家人
 */
-(void)addBtnClicked
{
    MyNSLog("添加");
    
    if (self.myFamilyDataArray.count <18) {
        AddFamilyViewController *addFamily = [[AddFamilyViewController alloc] init];
        [self.navigationController pushViewController:addFamily animated:YES];
    }else{
        
        [self showCustomHudSingleLine:@"家人人数已达上限"];
    }
   
    
}
#pragma mark - 加载数据
-(void)loadData
{
    self.myFamilyDataArray = [NSMutableArray arrayWithCapacity:0];
    self.relationShipArray = @[@"",@"祖父母", @"父母",@"其他平辈", @"子女", @"孙辈",@"爱人"];//这个是为了让pickerview的data+1好与上传服务器参数一致
    //我自己的个人信息
    UserModel * model =[[UserManager shareInstance]getUserInfo];
    self.userId = model.uid;
    self.myName = model.username;
    //请求标志
    self.AFNetFlag = 0;
    //下面的事交给viewWillAppear
    
    
//    //请求我自己的用药提醒
//    [self AFNetRequestForMyDrugReminderCount];
//    //请求家人数据
//    [self AFNetRequestWithAllFamilyName];
}
#pragma mark - AFNet--网络请求所有家人信息
//这里获取到家人的fid，名字，是否有用药提醒，家人头像
-(void)AFNetRequestWithAllFamilyName
{
    [self showActionView];
    NSString *postURL = [NSString stringWithFormat:@"%@user/home/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        if (self.AFNetFlag == 1) {//先判断标志是否是1，如果是1就hidden菊花
            [self hiddenActionView];
        }else
        {
            self.AFNetFlag = 1;//不是1，说明还有另一个请求没有接受，把这个标志设为1，告知，当前请求结束
        }
        
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            [self.myFamilyDataArray removeAllObjects];
            [self.tableView reloadData];
        }else
        {
            [self.myFamilyDataArray removeAllObjects];
            for (NSDictionary *dic  in [responseObject objectForKey:@"data"]) {
                AllFamilyModal *modal = [[AllFamilyModal alloc] initWithDic:dic];
                [self.myFamilyDataArray addObject:modal];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("失败");
        if (self.AFNetFlag == 1) {
            [self hiddenActionView];
        }else
        {
            self.AFNetFlag = 1;
        }
    }];
}

#pragma mark - 创建tableView
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
  
    [self.tableView  setSeparatorColor:CellLineColor];

}

#pragma mark - tableView的代理放法
//多少段
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.myFamilyDataArray.count !=0)//有家人是2段
    {
        return 2;
    }
    else//没有家人是1段
    {
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        if (IPhone6Plus) {
            return 12;
        }else{
            return 10;
        }
    }
    else
    {
        if (IPhone6Plus) {
            return 40;
        }else{
            return 35;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (IPhone6Plus) {
        return 53;
    }else{
        return 44;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
//段头视图
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {

        return nil;
    }
    else
    {
        CGFloat viewHeight = 35;
        CGFloat viewLeft = 15;
        CGFloat textFont = 13;
        if (IPhone6Plus) {
            viewHeight = 40;
            viewLeft = 20;
            textFont = 15;
        }
        
        self.myFamilyHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewHeight)];
        self.myFamilyHeaderView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        UILabel *myFamily = [[UILabel alloc] initWithFrame:CGRectMake(viewLeft, 0, 100, viewHeight)];
        myFamily.text = @"我的家人";
        myFamily.font = [UIFont systemFontOfSize:textFont];
        myFamily.textColor = [UIColor grayColor];
        [self.myFamilyHeaderView addSubview:myFamily];
        return self.myFamilyHeaderView;
    }
    
}
//各段有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //第一段肯定是1行，显示我的提醒
    if (section == 0)
    {
        return 1;
    }
    else//第二段根据家人个数显示
    {
        return self.myFamilyDataArray.count;
    }
}
#pragma mark ----加载cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TakeDrugCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        if (IPhone6Plus) {
             cell = [[[NSBundle mainBundle] loadNibNamed:@"TakeDrugCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TakeDrugCell" owner:self options:nil] firstObject];
        }
    }
    cell.jumpImgView.left = kScreenWidth-30;
    if (IPhone6Plus) {
        cell.jumpImgView.left = kScreenWidth-35;
    }
    cell.remindLable.right = cell.jumpImgView.left-5;
    
    [cell.jumpImgView setImage:[UIImage imageNamed:@"公用_跳转.png"]];
    //第一段-->"我"
    if (indexPath.section == 0)
    {
        //获取我自己个人信息
        UserModel * model =[[UserManager shareInstance]getUserInfo];
        //用户自己的真实姓名为空的话就只显示"我"
        if (model.realname.length == 0) {
            cell.nameLable.text = @"我";
        }
        else
        {
            cell.nameLable.text = [NSString stringWithFormat:@"我(%@)",model.realname];//我（真实名字）//这里应该是真实名字
        }
        if (self.myDrugReminderDataArray.count != 0 ) {
            cell.remindLable.text = [NSString stringWithFormat:@"%ld个提醒",self.myDrugReminderDataArray.count];
        }else
        {
            cell.remindLable.text = @"无提醒";
        }
        
    }
    else//第二段“我的家人”
    {
        //加载数据
        AllFamilyModal * modal = [self.myFamilyDataArray objectAtIndex:indexPath.row];
        cell.nameLable.text = [NSString stringWithFormat:@"%@(%@)",[self.relationShipArray objectAtIndex:[modal.type intValue]],modal.realname];
      
        if ([modal.drugcount intValue]==0) {
            cell.remindLable.text = @"无提醒";
        }else
        {
            cell.remindLable.text = [NSString stringWithFormat:@"%d个提醒",[modal.drugcount intValue]];
        }
    }
    
    return cell;
}
#pragma mark - 选中某一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击某一行都是进入--用药提醒--药品列表页面
    TakeDrugReminderViewController *drugReminder = [[TakeDrugReminderViewController alloc] init];
    drugReminder.navBarTitle = @"用药提醒";
    drugReminder.MedicalRecord = @"没有病历";
    
    if (indexPath.section == 0)//第一段是"我"
    {
        UserModel * modal =[[UserManager shareInstance]getUserInfo];
        
        //我自己--把我的信息传过去--fid传自己的uid，type=7
        drugReminder.peopleDic = @{@"realname":modal.realname,@"uid":modal.uid,@"fid":modal.uid,@"avatar":modal.avatar,@"username":modal.username,@"type":@"7",@"gender":modal.gender};
        
    }
    else//第二段---是我的家人列表，
    {
        self.selectedCell = (TakeDrugCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        //点击家人列表--把该家人的信息modal传过去
        AllFamilyModal * modal = [self.myFamilyDataArray objectAtIndex:indexPath.row];
        
        MyNSLog("%@", modal.avatar);
        drugReminder.peopleDic = @{@"uid":modal.uid,@"fid":modal.fid,@"username":modal.username,@"realname":modal.realname,@"avatar":modal.avatar,@"type":modal.type,@"birthday":modal.birthday,@"gender":modal.gender,@"idcard":modal.idcard,@"mobile":modal.mobile};
        
    }
    
    [self.navigationController pushViewController:drugReminder animated:YES];
}
#pragma mark - AFNet请求我自己的用药提醒
-(void)AFNetRequestForMyDrugReminderCount
{
    [self showActionView];
    UserModel * model =[[UserManager shareInstance]getUserInfo];
    //即使网络连接失败也需要获取从本地把自己的提醒取出来
    NSUserDefaults *myDrugReminderUser = [NSUserDefaults standardUserDefaults];
    self.myDrugReminderDataArray = [myDrugReminderUser objectForKey:[NSString stringWithFormat:@"MyDrugReminder%@",model.uid]];
    //
    NSString *postURL = [NSString stringWithFormat:@"%@user/drug/",kBaseURL];
    NSDictionary * parameters = @{@"platform":kPlatform,@"version":kVersion,@"uid":model.uid,@"fid":model.uid};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (self.AFNetFlag == 1) {
            [self hiddenActionView];
        }else
        {
            self.AFNetFlag = 1;
        }
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]){
            
            MyNSLog("没有数据%@", responseObject[@"msg"]);
            NSUserDefaults *myDrugReminderUser = [NSUserDefaults standardUserDefaults];
            [myDrugReminderUser removeObjectForKey:[NSString stringWithFormat:@"MyDrugReminder%@",model.uid]];
            [myDrugReminderUser synchronize];
            self.myDrugReminderDataArray = @[];
            [self.tableView reloadData];
            
            
        }else
        {
            MyNSLog("%@", responseObject);
            self.myDrugReminderDataArray = responseObject[@"data"];
            //网络请求成功后把这个用药提醒存入本地，刷新自己的本地数据
            NSUserDefaults *myDrugReminderUser = [NSUserDefaults standardUserDefaults];
            [myDrugReminderUser setObject:self.myDrugReminderDataArray forKey:[NSString stringWithFormat:@"MyDrugReminder%@",model.uid]];
            [myDrugReminderUser synchronize];
            
            [self.tableView reloadData];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("我的个人用药提醒网络失败");
        if (self.AFNetFlag == 1) {
            [self hiddenActionView];
        }else
        {
            self.AFNetFlag = 1;
        }
        
    }];
}

@end
